<template>
  <div>
    <!-- 欢迎卡片 -->
    <el-card class="welcome-card" shadow="hover">
      <div class="welcome-content">
        <el-avatar :size="64" class="welcome-avatar">
          <i class="el-icon-user-solid"></i>
        </el-avatar>
        <div class="welcome-text">
          <div class="welcome-title">欢迎回来，投标单位</div>
          <div class="welcome-subtitle">
            今天是 {{ currentDate }}，祝您工作愉快！
          </div>
        </div>
      </div>
    </el-card>

    <!-- 询标列表 -->
    <el-card class="list-card" shadow="hover">
      <div slot="header" class="card-header">
        <span class="card-title">询标列表</span>
        <el-input
          v-model="search"
          placeholder="编号搜索"
          prefix-icon="el-icon-search"
          clearable
          class="search-input"
        />
      </div>

      <div class="card-content">
        <!-- 状态筛选 -->
        <div class="status-filter">
          <el-radio-group v-model="selectedStatus" class="status-group">
            <el-radio-button
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.value"
            >
              {{ status.text }}
            </el-radio-button>
          </el-radio-group>
        </div>

        <!-- 表格 -->
        <el-table
          :data="filteredInquiries"
          v-loading="loading"
          element-loading-text="加载中..."
          class="inquiry-table"
          empty-text="暂无数据"
          :fit="true"
          style="width: 100%"
        >
          <el-table-column prop="InquiryNo" label="询标编号">
            <template slot-scope="scope">
              <el-link
                type="primary"
                :underline="false"
                @click="goToInquiryDetail(scope.row)"
              >
                {{ scope.row.InquiryNo }}
              </el-link>
            </template>
          </el-table-column>

          <el-table-column prop="ProjectNo" label="项目编号" />

          <!-- <el-table-column prop="InquiryContent" label="询标内容" min-width="200">
            <template slot-scope="scope">
              <div
                class="content-cell"
                :title="scope.row.InquiryContent"
              >
                {{ scope.row.InquiryContent }}
              </div>
            </template>
          </el-table-column> -->

          <el-table-column prop="DeadlineTime" label="截止时间">
            <template slot-scope="scope">
              <span :class="{ 'expired-time': isExpired(scope.row.DeadlineTime) }">
                {{ scope.row.DeadlineTime }}
              </span>
            </template>
          </el-table-column>

          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-tag
                :type="getStatusColor(scope.row)"
                size="small"
              >
                {{ getStatusText(scope.row) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                plain
                @click="goToInquiryDetail(scope.row)"
              >
                <i class="el-icon-view"></i>
                查看
              </el-button>
              <el-button
                type="primary"
                size="mini"
                plain
                :disabled="isButtonDisabled(scope.row)"
                @click="replyInquiry(scope.row)"
              >
                <i class="el-icon-edit"></i>
                回复
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-size="itemsPerPage"
            :total="totalItems"
            layout="total, prev, pager, next, jumper"
            background
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { GetBidderInquiryList } from '@/api/BidderInquiry'

export default {
  name: 'InquiryList',

  data() {
    return {
      search: '',
      loading: false,
      selectedStatus: '0',
      page: 1,
      itemsPerPage: 10,
      totalItems: 0,
      inquiries: [],
      statusOptions: [
        { text: '全部', value: '0' },
        { text: '待回复', value: '1' },
        { text: '已回复', value: '2' },
        { text: '已截止', value: '3' }
      ],
      headers: [
        { text: '询标编号', value: 'InquiryNo' },
        { text: '项目编号', value: 'ProjectNo' },
        // { text: '询标内容', value: 'InquiryContent' },
        { text: '截止时间', value: 'DeadlineTime' },
        { text: '状态', value: 'status' },
        { text: '操作', value: 'actions', sortable: false }
      ]
    }
  },

  computed: {
    currentDate() {
      return new Date().toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      })
    },
    pageCount() {
      return Math.ceil(this.totalItems / this.itemsPerPage)
    },
    filteredInquiries() {
      if (!this.search) {
        return this.inquiries
      }
      const keyword = String(this.search || '').toLowerCase();
      return this.inquiries.filter(item => {
        const projectNo = item && item.ProjectNo != null ? String(item.ProjectNo).toLowerCase() : '';
        const projectName = item && item.ProjectName != null ? String(item.ProjectName).toLowerCase() : '';
        const inquiryContent = item && item.InquiryContent != null ? String(item.InquiryContent).toLowerCase() : '';
        return (
          projectNo.indexOf(keyword) !== -1 ||
          projectName.indexOf(keyword) !== -1 ||
          inquiryContent.indexOf(keyword) !== -1
        );
      })
    }
  },

  watch: {
    page() {
      this.fetchData()
    },
    itemsPerPage() {
      this.page = 1
      this.fetchData()
    },
    selectedStatus() {
      this.page = 1
      this.fetchData()
    },
    search() {
      this.page = 1
      this.fetchData()
    }
  },

  mounted() {
    // 先从 URL 中读取 token 并写入 localStorage，再拉取数据
    this.initTokenFromUrl()
    this.fetchData()
  },

  methods: {
    // 首次进入读取地址栏 token（支持 token/Token/access_token），写入本地并清理 URL
    initTokenFromUrl() {
      const q = this.$route.query || {}
      const urlToken = q.token || q.Token || q.access_token
      if (urlToken) {
        try {
          // 直接写入本地；request 拦截器会自动带上 Authorization: Bearer <token>
          localStorage.setItem('token', urlToken)
          sessionStorage.setItem('token', urlToken)
        } catch (e) {
          console.warn('保存 token 失败:', e)
        }

        // 清理地址栏中的 token，避免泄漏
        const newQuery = { ...q }
        delete newQuery.token
        delete newQuery.Token
        delete newQuery.access_token
        this.$router.replace({ path: this.$route.path, query: newQuery }).catch(() => {})
      }
    },

    async fetchData() {
      this.loading = true
      try {
        const params = {
          pageIndex: this.page,
          pageSize: this.itemsPerPage,
          type: this.selectedStatus,
          key: this.search
        }
        const res = await GetBidderInquiryList(params)
        if (res.Data && res.Data.IsSuccess === false) {
          alert(res.Data.Message)
          return
        }
        this.inquiries = res.Data.Data || []
        this.totalItems = res.Data.Count || 0
      } catch (err) {
        console.error('获取询标列表失败', err)
      } finally {
        this.loading = false
      }
    },

    getStatusColor(item) {
      if (!item.IsReply && this.isExpired(item.DeadlineTime)) {
        return 'danger'
      }
      return item.IsReply ? 'success' : 'warning'
    },

    getStatusText(item) {
      if (!item.IsReply && this.isExpired(item.DeadlineTime)) {
        return '已截止'
      }
      return item.IsReply ? '已回复' : '待回复'
    },

    isExpired(deadline) {
      return new Date(deadline) < new Date()
    },

    isButtonDisabled(item) {
      return this.isExpired(item.DeadlineTime) || item.IsReply
    },

    goToInquiryDetail(item) {
      this.$router.push({
        name: 'expert-inquiry-detail',
        query: { Id: item.Id, t: Date.now() }
      })
    },

    replyInquiry(item) {
      this.$router.push({
        path: '/bidder/home',
        query: {
          Id: item.Id,
          ProjectNo: item.ProjectNo
        }
      })
    },

    handleCurrentChange(currentPage) {
      this.page = currentPage
      this.fetchData()
    }
  }
}
</script>

<style scoped>
.welcome-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.welcome-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.welcome-content {
  display: flex;
  align-items: center;
  padding: 16px;
}

.welcome-avatar {
  margin-right: 16px;
  background: #409eff !important;
}

.welcome-text {
  flex: 1;
}

.welcome-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #303133;
}

.welcome-subtitle {
  font-size: 14px;
  color: #909399;
}

.list-card {
  transition: all 0.3s ease;
}

.list-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.search-input {
  width: 240px;
}

.card-content {
  padding: 0;
}

.status-filter {
  margin-bottom: 20px;
  padding: 16px 0;
}

.status-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.inquiry-table {
  margin-bottom: 20px;
  width: 100%;
}

.content-cell {
  max-width: 280px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.expired-time {
  color: #f56c6c;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 16px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .welcome-content {
    flex-direction: column;
    text-align: center;
  }
  
  .welcome-avatar {
    margin-right: 0;
    margin-bottom: 12px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .status-group {
    justify-content: center;
  }
}

@media (max-width: 600px) {
  .welcome-title {
    font-size: 16px;
  }
  
  .welcome-subtitle {
    font-size: 12px;
  }
  
  .card-title {
    font-size: 16px;
  }
}
</style>